#ifndef TC_MAVARIABLE_HPP
#define TC_MAVARIABLE_HPP

/** \file MAVariable.hpp
 * Definition for the MAVariable function template.
 *
 * (C) Copyright 2003-2006 by Semih Cemiloglu
 * All rights reserved, see COPYRIGHT file for details.
 *
 * $Id: MAVariable.hpp 110 2006-06-19 03:38:33Z semihc $
 *
 *
 */

#include <vector>
#include "TA.hh"
#include "DBC.hpp"
#include "ChandeOscillator.hpp"

namespace TC {

  //! Triangular moving average function.
  TC_EXPORT template <typename InputIterator,
                      typename OutputIterator,
                      class Adaptor>
  void MAVariable(InputIterator fromPos,
		  InputIterator fromEnd,
		  OutputIterator toPos,
		  const unsigned period,
		  const Adaptor adaptor)
  {
    TC_PRE_CONDITION(period > 0);

    // Chande Momentum Oscillator values
    std::vector<TAfp_t> cmo_vec;

    ChandeOscillator(fromPos, fromEnd, 
		     std::back_inserter(cmo_vec),
		     9, // by definition 9 period
		     ArrayAdaptor<TAfp_t>());

    // Scaling Multiplier
    const TAfp_t sm = 2.0 / (period+1);
    // Volatility Ratio
    register TAfp_t vr;
    // Current, previous Moving Average
    register TAfp_t ma = adaptor(*fromPos);

    register unsigned i;
    for(i=0; fromPos!=fromEnd; ++i,++fromPos) {
      // Calculate volatility ratio
      vr = cmo_vec[i];
      if(vr > 0)
	vr /= 100.0;
      else
	vr /= -100.0;
      // Calculate Moving Average
      ma = (sm*vr*adaptor(*fromPos)) + ((1.0 - (sm*vr))*ma);
      *toPos++ = ma;
    } // end for
    
  }


} // end namespace


#endif /* Include guard */
